package com.study.rabbitmq2.basic1;

import com.rabbitmq.client.*;
import com.study.rabbitmq2.util.ConnectionUtil;

import java.io.IOException;

/**
 * @Author chenyeqing
 * @Date 2021/11/21 14:53
 */
public class Recv2 {

    private final static String QUEUE_NAME = "simple_queue";

    public static void main(String[] args) throws IOException {
        // 获取连接
        Connection connection = ConnectionUtil.getConnection();

        // 创建通道 final是因为内部类中访问
        final Channel channel = connection.createChannel();

        try {
            // 声明队列
            channel.queueDeclare(QUEUE_NAME, false, false, false, null);
        } catch (IOException e) {
            e.printStackTrace();
        }

        DefaultConsumer consumer = new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                // int i = 3 / 0;
                String msg = new String(body);
                System.out.println("[x] received:" + msg);

                /**
                 * 手动进行ACK
                 * deliveryTag 用来表示消息的id
                 * multiple 是否批量 true：确认所有消息
                 */
                channel.basicAck(envelope.getDeliveryTag(), false);
            }
        };

        // 监听队列，第二个参数false，手动进行ACK
        channel.basicConsume(QUEUE_NAME, false, consumer);
    }
}
